package leetcode.f1t100;

/**
 * 按numRows 输出 s 的特定格式
 * Input: s = "PAYPALISHIRING", numRows = 4
 * Output: "PINALSIGYAHRPI"
 * Explanation:
 * P     I    N
 * A   L S  I G
 * Y A   H R
 * P     I
 *
 * https://leetcode.com/problems/zigzag-conversion/
 *
 * @author lichx
 * @date 2021/9/24 14:50
 */
public class Q6_ZigZagConversion {
    public String convert(String s, int numRows) {
        return f1(s, numRows);
    }

    public String f1(String s, int m) {
        if(m==1){
            return s;
        }
        char[] c = s.toCharArray();
        int N = c.length;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < m; i++) {
            int nextStep = i;
            if(i==0 || i==m-1){
                while(nextStep < N){
                    sb.append(c[nextStep]);
                    nextStep += (m-1)*2;
                }
            }else {
                int cursor = 0;
                while (nextStep < N) {
                    sb.append(c[nextStep]);
                    cursor += (m - 1);
                    nextStep = cursor + (m - i-1);
                    if (nextStep < N) {
                        sb.append(c[nextStep]);
                        cursor += (m - 1);
                        nextStep = cursor + i;
                    }
                }
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Q6_ZigZagConversion a = new Q6_ZigZagConversion();
        System.out.println(a.convert("PAYPALISHIRING",3));
        System.out.println("PAHNAPLSIIGYIR");
    }
}
